<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const books = ref([])
const loading = ref(true)
const error = ref(null)

const fetchBooks = async () => {
  try {
    loading.value = true
    error.value = null
    const response = await axios.get('/api/Book')
    // console.log('API 响应状态码:', response.status)
    // console.log('API 响应头:', response.headers)
    // console.log('API 完整响应对象:', response)
    // console.log('图书数据结构:', {
    //   数据类型: typeof response.data,
    //   是否为数组: Array.isArray(response.data),
    //   数据长度: Array.isArray(response.data) ? response.data.length : '非数组'
    // })
    // console.log('图书数据内容:', response.data)
    books.value = response.data.data
  } catch (err) {
    error.value = '获取图书数据失败: ' + err.message
    console.error('获取图书数据失败详情:', {
      错误消息: err.message,
      错误名称: err.name,
      响应状态: err.response?.status,
      响应数据: err.response?.data
    })
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchBooks()
})
</script>

<template>
  <div class="book-list">
    <h1>图书列表</h1>
    <div v-if="loading" class="loading">
      加载中...
    </div>
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    <div v-else class="books">
      <div v-for="book in books" :key="book.id" class="book-item">
        <h3>{{ book.title }}</h3>
        <p>作者：{{ book.author }}</p>
        <p>价格：¥{{ book.price }}</p>
        <p>出版日期：{{ new Date(book.publishDate).toLocaleDateString() }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.book-list {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading,
.error {
  text-align: center;
  padding: 20px;
  font-size: 1.2em;
}

.error {
  color: #dc3545;
}

.books {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.book-item {
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 15px;
  background-color: var(--color-background-soft);
}

.book-item h3 {
  margin: 0 0 10px 0;
  color: var(--color-heading);
}

.book-item p {
  margin: 5px 0;
  color: var(--color-text);
}
</style>